<template>
  <view class="pr-container">
    <t-header @back="back"
      >{{ title }}

      <!-- <template #right>
        <navigator
          slot="right"
          class="text-orange"
          :url="'/pages/shares/dzyj-record-dy?name=' + title"
        >
          记录
        </navigator>
      </template> -->
    </t-header>

    <div class="content">
      <view class="flex head">
        <view class="col-4 text-center"> 股票名称 </view>
        <view class="col-4 text-center"> 涨跌幅(%) </view>
        <view class="col-4 text-center">
          <!-- 总股额(股) -->
          现价
        </view>
        <view class="col-4 text-center"> 操作 </view>
      </view>

      <mescroll-uni
        @init="mescrollInit"
        :down="downOption"
        @down="downCallback"
        height="90%"
        :up="upOption"
        @up="upCallback"
      >
        <view class="item" v-for="(item, index) in list" :key="index">
          <view class="flex align-center">
            <view class="col-4">
              <view>{{ item.title }}</view>
              <view class="flex align-center">
                <image
                  class="sign"
                  :src="`/static/images/icons/${item.marketCode}.png`"
                  mode=""
                ></image>
                <view class="text-sm">{{ item.code }}</view>
              </view>
            </view>
            <view class="col-4 text-center">
              {{ item.cai_pricechange }}
            </view>
            <view class="col-4 text-center">
              <!-- {{formatNumberUnit(item.totalzfanum)}} -->
              {{ item.cai_price }}
            </view>
            <view class="col-4 flex justify-center">
              <tui-button
                @click="showBuy"
                :index="index"
                type="theme"
                shape="circle"
                :size="28"
                width="100rpx"
                height="60rpx"
                >买入</tui-button
              >
            </view>
          </view>

          <!-- <view class="flex align-center padding-top-sm padding-lr-sm">
					<view class="progress">
						<view class="bar" :style="{width: item.progress}"></view>
					</view>
					<view class="text-sm text-gray">
						{{
							formatNumberUnit(item.zfanum)
						}}
					</view>
				</view> -->
        </view>
      </mescroll-uni>
    </div>

    <tui-modal
      :show="showModal"
      custom
      @cancel="showModal = false"
      padding="40rpx"
    >
      <view class="" v-if="currentItem">
        <view class="cell">
          <view>股票名称</view>
          <view>{{ currentItem.title }}</view>
        </view>
        <view class="cell">
          <view>股票代码</view>
          <view>{{ currentItem.code }}</view>
        </view>
        <view class="cell">
          <view>当前价</view>
          <view>{{ currentItem.cai_buy }}</view>
        </view>
        <view class="cell">
          <view>可用余额</view>
          <view>{{ userInfo.property_money }}</view>
        </view>
        <view class="cell">
          <view>最大购买</view>
          <view>{{ currentItem.max_num }}</view>
        </view>
        <view class="cell">
          <view>支付金额</view>
          <view>{{ frozenMoey || 0 }}</view>
        </view>
        <view class="cell">
          <view>数量(手)</view>
          <view>
            <tui-numberbox
              :max="max"
              :value="handNum"
              @change="changeHandNum"
            ></tui-numberbox>
          </view>
        </view>
        <view class="cell" v-if="currentItem.conditioncode">
          <view>密钥</view>
          <view>
            <tui-input
              type="password"
              v-model="miyao"
              :labelSize="28"
              :size="28"
              placeholder="请输入密钥"
            ></tui-input>
          </view>
        </view>
      </view>

      <!-- <tui-divider>1手100股</tui-divider> -->

      <view class="flex justify-around margin-top">
        <tui-button
          @click="showModal = false"
          type="theme"
          plain
          width="160rpx"
          height="80rpx"
          :size="30"
          >取消</tui-button
        >
        <tui-button
          :loading="submiting"
          :disabled="submiting"
          @click="buy"
          type="theme"
          width="160rpx"
          height="80rpx"
          :size="30"
          >确定</tui-button
        >
      </view>
    </tui-modal>
  </view>
</template>

<script setup>
  import { ref, nextTick, computed, onMounted } from 'vue';
  import { useUserStore, useMainStore } from '@/store';
  import { onLoad, onShow } from '@dcloudio/uni-app';

  import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
  import { tradeDyList, tradeDyAdd } from '@/api/index.js';
  import {
    getMarketCode,
    formatNumberUnit,
    getAllCode,
    getShortCode,
    manyAccAdd,
    manyAccMul,
  } from '@/utils/stock.js';
  import tui from '@/common/httpRequest.js';

  import THeader from '@/components/views/t-header/index.vue'; // 头部组件

  // mescroll-uni不用传onPageScroll, onReachBottom
  const { mescrollInit, downCallback, getMescroll } = useMescroll(); // 调用mescroll的hook

  const title = ref('VIP调研票1');
  onLoad((t) => {
    if (t.name) {
      title.value = t.name;
    }
  });

  const store = useUserStore();
  const mainStore = useMainStore();
  console.log('store', store);
  const userInfo = computed(() => store.$state.userInfo);
  const sysConfig = computed(() => mainStore.$state.sysConfig);

  const upOption = {
    auto: true, // 不自动加载
    noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
    empty: {
      tip: '~ 暂无数据 ~', // 提示
      // btnText: '去看看',
    },
  };

  const downOption = {
    auto: false, //
  };

  onShow(() => {
    store.syncUserInfo();
  });

  onMounted(() => {
    // this.mescrollInitByRef(); // 兼容字节跳动小程序, 避免未设置@init或@init此时未能取到ref的情况
  });

  const list = ref([]);
  const upCallback = (mescroll) => {
    //联网加载数据
    tradeDyList({
      page: mescroll.num,
      size: mescroll.size,
    }).then((res) => {
      if (mescroll.num == 1) list.value = [];
      if (res.data.list) {
        res.data.list.forEach((v) => {
          v.marketCode = getMarketCode(v.allcode);
          v.progress = (v.totalbuy * 100) / v.totalzfanum + '%';
        });
      }

      list.value = list.value.concat(res.data.list);
      mescroll.endSuccess(res.data.list.length);
    });
  };

  // 买入数量修改
  const handNum = ref(0);
  const changeHandNum = (e) => {
    handNum.value = e.value;
  };

  // 显示买入
  const currentItem = ref(null);
  const showModal = ref(false);
  const showBuy = (e) => {
    let i = e.index;
    currentItem.value = list.value[i];
    nextTick(() => {
      showModal.value = true;
    });
  };

  // 购买
  const frozenMoey = computed(() => {
    return currentItem.value
      ? manyAccMul(handNum.value, 100, currentItem.value.cai_buy)
      : 0;
  });
  const miyao = ref('');
  const submiting = ref(false);
  const buy = (e) => {
    if (handNum.value == 0 || handNum.value == '') {
      tui.toast('请输入正确的手数');
      return;
    }
    if (currentItem.value.conditioncode && !miyao.value) {
      tui.toast('请输入正确的密钥');
      return;
    }
    let postData = {
      code: getShortCode(currentItem.value.allcode),
      allMoney: manyAccMul(
        sysConfig.dz_dzsxf,
        handNum.value,
        100,
        currentItem.value.cai_buy
      ), //综合费用手续费
      allcode: getAllCode(currentItem.value.allcode), //
      buyprice: currentItem.value.cai_buy, //买入价
      canBuy: handNum.value, //手数
      cityValue: frozenMoey.value, //市值
      is_auto_money: 1, //自动续费设置:0=否,1=是
      is_buy: 1,
      is_sell: 0,
      losePrice: 0, //止损价
      money: manyAccAdd(
        frozenMoey.value,
        manyAccMul(
          sysConfig.value.dz_dzsxf,
          handNum.value,
          100,
          currentItem.value.cai_buy
        )
      ), //本金 + 手续费
      multiplying: 1, //倍率，
      number: handNum.value * 100, //购买股数量
      profitPrice: 0, //止盈价
      recommendnum: frozenMoey.value,
      strategy_id: getAllCode(currentItem.value.allcode), //股票全code 比如 sz300533 带字母
      title: currentItem.value.title,
      creditMoney: frozenMoey.value,
      miyao: miyao.value,
      jiami: 1,
    };
    submiting.value = true;
    tradeDyAdd(postData).then((res) => {
      tui.modal(null, res.msg, false, () => {
        submiting.value = false;
        if (res.code == 1) {
          // 判断是否是 开启了委托 如果开启了委托 跳入委托记录
          // url:this.sysConfig.is_weituo==1?'/pages/ucenter/entrust':'/pages/ucenter/holding'
          if (sysConfig.value.is_weituo == 1) {
            uni.redirectTo({
              url: '/pages/ucenter/entrust',
            });
          } else {
            uni.redirectTo({
              url: './dzyj-record-dy',
            });
          }
        } else {
          submiting.value = false;
        }
      });
    });
  };

  // 最大数
  const max = computed(() => {
    let num = 0;
    if (currentItem.value) {
      //最大购买量
      let max = parseInt(
        (userInfo.property_money / currentItem.value.cai_buy) * 100
      );
      if (max > currentItem.value.max_num) {
        max = currentItem.value.max_num;
      }
      num = max;
    }
    return num;
  });

  const back = () => {
    uni.navigateBack();
  };

  const clickNavBackFn = () => {
    const pages = getCurrentPages();
    if (pages.length >= 2) {
      uni.navigateBack();
    } else {
      uni.switchTab({
        url: '/pages/my/index',
      });
    }
  };
</script>

<style lang="scss" scoped>
  .pr-container {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    width: 100vw;
    height: 100vh;
    // padding: 84rpx 18rpx 26rpx;
    background: #f5f5f5;
  }

  .content {
    flex: 1;
    height: 0;
    background: #fff;
    border-radius: 34rpx;
    padding: 16rpx 20rpx;
    margin: 0 18rpx;
  }
  .head {
    padding: 16rpx 0;
    font-size: 28rpx;
    color: #999;
    margin-top: 10rpx;
    border-bottom: 2rpx solid #e2e2e2;

    // margin-bottom: 10rpx;
  }
  .item {
    padding: 20rpx;
    background: #fff;
    border-bottom: 1px solid #f2f2f2;
    .sign {
      width: 36rpx;
      height: 24rpx;
      margin-right: 6rpx;
    }
  }
  .progress {
    position: relative;
    flex: 1;
    margin-right: 10rpx;
    height: 20rpx;
    border-radius: 20rpx;
    background: #f7f7f7;
    overflow: hidden;
    .bar {
      position: absolute;
      background: #ef4942;
      left: 0;
      top: 0;
      height: 100%;
    }
  }
  .cell {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    justify-content: space-between;
    view:first-child {
      color: #999;
    }
  }
</style>
